/**
 * @author spf
 */
export default {
  data() {
    return {
      list: [], // 数据
      page: 1, // 当前页码
      pageSize: 10, // 每页条数
      total: 0, // 总计数据条数
      pages: 0, // 总计页数
      loading: false, // 列表加载状态
      queryListFun: null, // 列表查询函数
      queryOneFun: null, // 查询单条函数
      deleteOneFun: null, // 删除单条函数
      addFun: null, // 添加单条数据函数
      updateFun: null, // 更新单条数据函数
      queryForm: {}, // 查询表单对象
      queryData: {}, // 查询表单对象
      form: {}, // 新增 / 修改表单对象
      cloneFormJSON: '', // 存储默认的表单对象JSON字符串 防止输入数据后或点击修改后再点击新增还是显示上次的数据
      drawer: {
        show: false, // 编辑抽屉是否显示
        type: null, // 当前操作类型(add / edit)
        title: '', // 标题
        confirmLoading: false, // 提交按钮加载状态
        id: null // 现在编辑的id
      },
      pageSizes: [10, 20, 30, 50, 100], // 可分页条数数组
      multipleSelection: [], // 多选数组
      validator: null, // 校验对象
      createdLoadData: true, // 是否在created里调用loadData函数
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer "/* + getToken()*/},
        // 上传的地址
        url: this.importURL
      },
      importURL: null
    }
  },
  created() {
    this.cloneFormJSON = JSON.stringify(this.form)
    this.beforeFirstLoadData && this.beforeFirstLoadData()
    if (this.createdLoadData)
      this.loadData({
        page: this.page,
        pageSize: this.pageSize
      })
  },
  /* onPullDownRefresh() {
    this.loadData({
      page: 1,
      pageSize: this.pageSize,
      query: this.query
    })
  },
  onReachBottom() {
    this.loadData({
      page: this.page + 1,
      pageSize: this.pageSize,
      query: this.query
    })
  },*/
  methods: {
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    loadData({
               page, pageSize
             }) {
      if (this.loading) {
        return
      }
      this.loading = true
      this.queryListFun({
        page, pageSize, params: this.queryForm, data: this.queryData
      }).then(res => {
        this.loading = false
        this.page = page
        this.pageSize = pageSize

        if (page === 1) {
          this.list = []
        }

        const {data, pages, total} = res
        this.list = data
        this.pages = pages
        this.total = total
      })
    },
    onClickSearch() {
      this.loadData({
        page: 1,
        pageSize: this.pageSize,
      })
    },
    onClickAdd() {
      this.drawer.show = true
      this.drawer.type = 'add'
      this.drawer.title = `添加${this.name}`

      this.form = JSON.parse(this.cloneFormJSON)
    },
    onClickEdit() {
      this.handleEdit(this.multipleSelection[0].id)
    },
    onDrawerClose() {
      this.drawer.show = false
    },
    onDrawerConfirm() {
      this.drawer.confirmLoading = true;
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          (this.drawer.type === 'edit' ? this.updateFun(this.drawer.id, this.form) : this.addFun(this.form)).then(res => {
            this.drawer.show = false
            this.loadData({
              page: this.drawer.type === 'edit' ? this.page : 1,
              pageSize: this.pageSize,
            })
          }).finally(_ => {
            this.drawer.confirmLoading = false
          })
        } else {
          this.drawer.confirmLoading = false
          this.$message({
            type: 'error',
            message: '请根据提示修改输入的内容'
          })
          return false;
        }
      });
    },
    handleSizeChange(val) {
      this.loadData({
        page: this.page,
        pageSize: val
      })
    },
    handleCurrentChange(val) {
      this.loadData({
        page: val,
        pageSize: this.pageSize
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleEdit(id) {
      this.drawer.show = true
      this.drawer.type = 'edit'
      this.drawer.title = `修改${this.name}`
      this.drawer.id = id
      this.queryOneFun(id).then(res => {
        for (let i in this.form) {
          this.form[i] = res.data[i]
        }
      })
    },
    handleDelete(id) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteOneFun(id).then(res => {
          this.loadData({
            page: this.page,
            pageSize: this.pageSize,
          })
          this.$message({
            type: 'success',
            message: res.msg
          })
        })
      })
    },
    resetQueryForm() {
      this.$refs.queryForm.resetFields()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.loadData({
        page: 1, pageSize: this.pageSize
      })
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`)
    },
    download() {
      this.dialogVisible = true
      this.showFileName = true
      this.operationType = 'download'
    },
  },
  computed: {
    editDisabled() {
      return this.multipleSelection.length !== 1
    },
    formRules() {
      if (this.validator === null)
        return {}
      return this.validator[(this.drawer.type === 'edit' ? 'insert' : 'update') + 'Rules']
    }
  }
}
